#! /usr/bin/env python3

import os
from urllib import parse


def file_tree(note_path, except_list):
    """
    Recect paths with a base path.
    """
    result = dict()
    for root, dirs, files in os.walk(note_path, topdown=False):
        if os.path.basename(root) in except_list:
            continue
        for name in files:
            if os.path.splitext(name)[-1] == ".md":
                temp = result
                full_path = os.path.join(root, name).lstrip(note_path)
                history_list = full_path.replace("\\", "/").split("/")
                i = 0
                while i <= (len(history_list) - 1):
                    if os.path.splitext(history_list[i])[-1] == ".md":
                        temp = temp.setdefault(full_path, "<md_file>")
                    else:
                        temp = temp.setdefault(history_list[i], dict())
                    i += 1
                temp = result
        for name in dirs:
            pass
    return result


def file_tree_with_html(execfile, note_path, except_list):
    def rec(temp_dict, html_list=list(), word_space=0):
        word_space += 4
        space = " " * (word_space - 1)
        html_list.append(space + "<ul>")
        i = 0
        while i < len(temp_dict):
            temp_list = list(temp_dict.keys())
            temp_list.sort()
            key = temp_list[i]
            value = temp_dict.get(key)
            sorted(value)
            if isinstance(value, dict):
                html_list.append(space + "<li class=\"floder\"><snap id=\"%s\">%s</li>" % (key, key))
                html_list = rec(
                    value,
                    html_list=html_list,
                    word_space=word_space)
            else:
                temp = "<li class=\"file\"><a href=\"%s\">%s</a></li>"
                tile = temp % (
                    execfile + "?file=" + parse.quote(key),
                    key.replace("\\", "/").split("/")[-1])
                html_list.append(space + tile)
            i += 1
        html_list.append(space + "</ul>")
        return html_list

    dict_tree = file_tree(note_path, except_list)
    html_re = rec(dict_tree)
    html = "\n".join(html_re)
    return html
